import axios from "axios"
import { Message } from "element-ui"
import qs from "qs"
import { isJSON } from "@/utils"
import { getToken, removeToken } from "@/utils/auth";
import router from "@/router"
import store from '@/store'
// 重复请求拦截，需要进行请求路由判断，否则无法并发请求
var CancelToken = axios.CancelToken
const pending = []
const cancelPending = (config) => {
  pending.forEach((item, index) => {
    if (config) {
      if (item.UrlPath === config.url) {
        item.Cancel() // 取消请求
        pending.splice(index, 1) // 移除当前请求记录
      }
    } else {
      item.Cancel() // 取消请求
      pending.splice(index, 1) // 移除当前请求记录
    }
  })
}

// 基本实例
const service = axios.create({
  headers: {
    "Content-Type": "application/json;charset=UTF-8",
  },
  baseURL: process.env.VUE_APP_BASE_API
})

service.interceptors.request.use(
   (request) => {
     const token = getToken()
     const userInfo = store.getters.userInfo
     if (token) {
       request.headers["authorization"] = token
     }
     if (userInfo) {
       request.headers["userInfo"] = encodeURIComponent(JSON.stringify(userInfo))
     }
     cancelPending(request)
     // 加入url判断是否重复请求
     request.cancelToken = new CancelToken((res) => {
       pending.push({ UrlPath: request.url, Cancel: res })
     })
     if (request.data && request.headers["Content-Type"] === "application/x-www-form-urlencoded" && Object.prototype.toString.call(request.data) === "[object Object]") {
       request.data = qs.stringify(request.data)
     }
     return request
   },
   (error) => {
     return Promise.reject(error)
   }
)

/**
 * @description 接口返回数据说明
 * @version 1.0.0
 * code 状态码 200 => success
 * msg 返回信息
 * data 请求数据
 */
// response 拦截器
service.interceptors.response.use(
   ({ data }) => {
     if (isJSON(data)) {
       data = JSON.parse(data)
     }
     if (data.success) {
       return data
     }
     if (!data.success) {
       Message.error(data.message)
       return
     }
     return data
   },
   (error) => {
     console.log('this1----error', error.response)
     if (error.response && error.response.status === 401) {
       Message.error('身份认证失败')
       removeToken()
       setTimeout(() => {
         router.push('login')
       }, 500)
     } else if (error.message) {
       Message.error(error.message)
       return Promise.reject(error)
     }
   }
)

export default service
